<template>
    <div class="cascader">
        <dl>
            <dt>省份/地区</dt>
            <dd>
                <ListItem :list="stateData.provList" :checkId="checkData.provId" level="0" @on-check="onclickItemHandler">
                </ListItem>
            </dd>
        </dl>
        <dl v-if="showCity">
            <dt>城市</dt>
            <dd>
                <ListItem :list="stateData.cityList" :checkId="checkData.cityId" level="1" @on-check="onclickItemHandler">
                </ListItem>
            </dd>
        </dl>
        <dl v-if="showArea">
            <dt>区/县</dt>
            <dd>
                <ListItem :list="stateData.areaList" :checkId="checkData.areaId" level="2" @on-check="onclickItemHandler">
                </ListItem>
            </dd>
        </dl>
        <dl>
            <dt>学校/单位</dt>
            <dd>
                <div class="cascader-search">
                    <el-input
                        v-model="requestData.schoolName"
                        placeholder="请输入关键词"
                        >
                        <template #append>
                            <el-button @click="searchSchool">搜索</el-button>
                        </template>
                    </el-input>
                </div>
                <div class="cascader-list" v-if="stateData.schooUnitlList.length">
                    <ul class="item-list" v-infinite-scroll="requestSchool" :infinite-scroll-disabled="disabled">
                        <li v-for="item in stateData.schooUnitlList" :key="item.schoolId" @click="checkSchool(item)" 
                            :class="['item', checkData.schoolId === item.schoolId ? 'focus' : '']">
                            <span>{{ item.schoolName }}</span>
                            <span class="label">{{ item.schoolAddress }}</span>
                        </li>
                        <p v-if="loading" class="load">加载中...</p>
                        <p v-if="noMore" class="load">没有更多数据了</p>
                    </ul>
                </div>
                <p v-if="isSearching && !stateData.schooUnitlList.length" class="no-data">暂未收录该地区的学校/单位</p>
            </dd>
        </dl>
    </div>
    <div class="cascader-dialog-footer">
        <el-button class="srt-el-button srt-el-button-h36" @click="cancel">取消</el-button>
        <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36" @click="confirm">确定</el-button>
    </div>
</template>

<script setup>
import ListItem from './fragment/list.vue'
import { reactive, onMounted, ref, computed } from 'vue'
import { useStore } from 'vuex';

const store = useStore();

const emit = defineEmits(['cancel', 'confirm']);

// 搜索
const isSearching = ref(false);

const requestData = ref({
    pageIndex: 1,
    pageSize: 10,
    schoolName: '', // 我创建的
})


const props = defineProps({
    type: { // school是学校 unit是单位
        type: String,
        default: 'school'
    },
    levelLimit: { // 1 省级 2市 3 区县
        type: [Number, String],
        default: 3
    },
    isShowRequset: {// 是否显示申请
        type: Boolean,
        default: true
    }
})

const stateData = reactive({
    provList: [],
    cityList: [],
    areaList: [],
    schooUnitlList: []
})

const loading = ref(false);

const total = ref(0);

const noMore = computed(() => stateData.schooUnitlList.length >= total.value);

const disabled = computed(() => loading.value || noMore.value)


const checkData = ref({
    provId: '',
    provName: '',
    cityId: '',
    cityName: '',
    areaId: '',
    areaName: '',
    schoolId: '',
    schoolName: ''
})

const typeCodeMap = {
    '0': 'prov',
    '1': 'city',
    '2': 'area',
    '3': 'school'
}

const listMap = {
    '0': 'provList',
    '1': 'cityList',
    '2': 'areaList',
    '3': 'schooUnitlList'
}

// 是否显示城市
const showCity = computed(() => {
    return props.levelLimit > 1;
})

// 是否显示区县
const showArea = computed(() => {
    return props.levelLimit > 2;
})


// 请求省市区
function requestRegion(params = {}) {
    G_transmit('requestRegion', {
        name: 'requestRegion',
        data: {
            ...params
        }
    }).then((res) => {
        let level = params?.level || '0';
        stateData[listMap[level]] = groupName(res.data);
    });
}

// 搜索学校
function searchSchool() {
    isSearching.value = true;
    requestData.value.pageIndex = 1;
    requestSchool();
}

// 请求学校
function requestSchool() {
    if(requestData.value.pageIndex === 1) {
        stateData.schooUnitlList = [];
    }
    loading.value = true;
    G_transmit('requestSchools', {
        name: 'requestSchools',
        queries: {
            schoolName: requestData.value.schoolName,
            cityCode: checkData.value.cityId,
            countryCode: checkData.value.areaId,
            provinceCode: checkData.value.provId,
            pageIndex: requestData.value.pageIndex,
            pageSize: requestData.value.pageSize
        }
    }).then((res) => {
        loading.value = false;
        isSearching.value = false;
        let tempList = res.data?.rows || [];
        stateData.schooUnitlList = [
            ...stateData.schooUnitlList,
            ...tempList,
        ];
        total.value = res.data?.total;
        if(stateData.schooUnitlList.length < total.value) {
            requestData.value.pageIndex++;
        }
    }).catch(_err => {
        loading.value = false;
        isSearching.value = false;
    });
}



// 解析省市区数据
function groupName(list) {
    const letters = 'abcdefghjklmnopqrstwxyz'.split('');
    const zh = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
    let segs = [];
    let curr;
    letters.forEach(function(letter, i) {
        curr = {
            letter,
            data: []
        };
        list.length && list.forEach(function(item) {
            if (zh[i]==item.letter.split('')[0]) {
                curr.data.push(item);
            }
        });
        if (curr.data.length) {
            segs.push(curr);
        }
    });
    return segs;
}

function onclickItemHandler({level, item}) {
    requestData.value.pageIndex = 1;
    requestData.value.schoolName = '';
    checkData.value[`${typeCodeMap[level]}Id`] = item.id;
    checkData.value[`${typeCodeMap[level]}Name`] = item.name;
    let nextLevel = Number(level) + 1;

    for(let i = nextLevel; i < 4; i++) { // 子集的数据置空
        checkData.value[`${typeCodeMap[i]}Id`] = '';
        checkData.value[`${typeCodeMap[i]}Name`] = ''; 
        stateData[listMap[i]] = [];
    }
    if(nextLevel < props.levelLimit) {
        requestData.value.schoolName = '';
        isSearching.value = false;
        requestRegion({level: nextLevel, pid: item.id});
    }else {
        requestSchool();
    }
}

// 选择学校数据
function checkSchool(item) {
    checkData.value.schoolId = item.schoolId;
    checkData.value.schoolName = item.schoolName;
}


// 取消
function cancel() {
    requestData.value.pageIndex = 1;
    clearData();
    emit('cancel');
}

// 确定
function confirm() {
    requestData.value.pageIndex = 1;
    emit('confirm', checkData.value);
    clearData();
}

function clearData() {
    stateData.cityList = [];
    stateData.areaList = [];
    stateData.schooUnitlList = [];
    requestData.value.schoolName = '';
    checkData.value = {};
}

onMounted(() => {
    requestRegion();
})

</script>

<style lang="scss" scoped>

$primary-color: var(--srt-color-primary);
$border-color: #e1e0e5;

.cascader {
    display: flex;
    border-radius: 4px;
    border: 1px solid $border-color;
    font-size: 12px;
    color: var(--srt-main-text-color);
    ul {
        list-style: none;
        padding: 0px;
        margin: 0px;
    }
    dl {
        flex: 1;
        list-style: none;
        padding: 0px;
        margin: 0px;

        &:last-child {
            flex: 2;
        }

        &:not(:first-child) {
            border-left: 1px solid $border-color;
        }

        dt {
            display: block;
            height: 37px;
            line-height: 37px;
            text-align: center;
        }

        dd {
            height: 260px;
            margin: 0px;
            overflow-y: auto;
            padding-top: 7px;
            border-top: 1px solid $border-color;
        }
    }

    .item {
        cursor: pointer;
        padding: 5px 0 5px 16px;

        &.focus {
            background: $primary-color;
            color: var(--srt-color-white);
            .label {
                color: var(--srt-color-white);
            }
        }

        .letter {
            display: inline-block;
            width: 16px;
            margin-right: 8px;
            text-align: center;
        }
    }
    .no-data {
        padding: 20px;
    }

    .cascader-search {
        margin: 0px 8px 8px 8px;
    }
}

textarea, input {
    &::-webkit-input-placeholder {
    /* WebKit browsers */
        color: var(--srt-color-light-gray);
    }
    &:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: var(--srt-color-light-gray);
    }
    &::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: var(--srt-color-light-gray);
    }
    &::-ms-input-placeholder {
        /* Internet Explorer 10+ */
        color: var(--srt-color-light-gray);
    }
}

.cascader-dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
.cascader-list {
    height: 210px;
    overflow-y: auto;
}
.item-list {
    .label {
        color: var(--srt-color-gray);
        display: block;
        font-size: 12px;
    }
}
.load {
    color: var(--srt-color-gray);
    padding: 5px 0px;
    text-align: center;
}
</style>